package com.glory.dgcpcpda.activity.check;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.dgcpcpda.R;
import com.glory.dgcpcpda.adapter.DataLinesAdapter;
import com.glory.dgcpcpda.adapter.ItemLinesAdapter;
import com.glory.dgcpcpda.adapter.ItemSpcLinesAdapter;
import com.glory.dgcpcpda.base.BaseActivity;
import com.glory.dgcpcpda.base.MyApp;
import com.glory.dgcpcpda.entity.AdrefListEntity;
import com.glory.dgcpcpda.entity.QCformEntity;
import com.glory.dgcpcpda.entity.SheetInfoEntity;
import com.glory.dgcpcpda.entity.response.BaseResponseBean;
import com.glory.dgcpcpda.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralFragmentDialog;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralPop;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DialogUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_PopUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_Utils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import org.json.JSONObject;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class QC_TaskExecuteNextActivity extends BaseActivity {


    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvBaseSubmit)
    TextView tvBaseSubmit;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.rvItemLines)
    RecyclerView rvItemLines;
    @BindView(R.id.rvDataLines)
    RecyclerView rvDataLines;
    @BindView(R.id.rvSpcLines)
    RecyclerView rvSpcLines;
    @BindView(R.id.etComment)
    FreeUI_ClearEditText etComment;
    @BindView(R.id.flType)
    FrameLayout flType;
    @BindView(R.id.ivType)
    ImageView ivType;
    @BindView(R.id.tvType)
    TextView tvType;
    @BindView(R.id.llType)
    LinearLayout llType;
    @BindView(R.id.flResultList)
    FrameLayout flResultList;
    @BindView(R.id.ivResultArrow)
    ImageView ivResultArrow;
    @BindView(R.id.tvResult)
    TextView tvResult;
    @BindView(R.id.llfinallyResultList)
    LinearLayout llfinallyResultList;
    @BindView(R.id.finallyResultList)
    FrameLayout finallyResultList;
    @BindView(R.id.ivfinallyResultArrow)
    ImageView ivfinallyResultArrow;
    @BindView(R.id.tvfinallyResult)
    TextView tvfinallyResult;
    @BindView(R.id.rvDatab)
    TextView rvDatab;
    @BindView(R.id.rvDatac)
    TextView rvDatac;

    private FreeUI_GeneralPop mTypePop;
    private FreeUI_GeneralPop mResultPop;
    private FreeUI_GeneralPop mfinallyResultPop;

    private ItemLinesAdapter mItemLinesAdapter;
    private DataLinesAdapter mDataLinesAdapter;
    private ItemSpcLinesAdapter mItemSpcLinesAdapter;
    private QCformEntity qCformEntity;
    private int itemPosition;
    private String LocationId = "";
    private String Type = "";
    private BigDecimal datanums=BigDecimal.ZERO;
    private ArrayList<String> typeList = new ArrayList<>();
    private ArrayList<String> resultList = new ArrayList<>();
    private ArrayList<String> finallyresultList = new ArrayList<>();


    @Override
    protected int getLayoutResId() {
        return R.layout.activity_taskexecute_next;
    }

    @Override
    protected void initView() {
        tvTitle.setText("QC首检巡检任务执行");
        setMainLayout(llMain);

    }

    @Override
    protected void initData() {
        Bundle bundle = getIntent().getExtras();
        qCformEntity = (QCformEntity) bundle.getSerializable("DATA");
        String ins = bundle.getString("INSPECTTIMING");
        LocationId = bundle.getString("LocationId");
        Type = bundle.getString("TYPE");
        datanums=qCformEntity.getQCFORM().getDATANUMS();
        if(Type.equals("首检")){
            finallyresultList.add("OK");
            finallyresultList.add("NG");
            llfinallyResultList.setVisibility(View.VISIBLE);
        }

        if (ins.equals("换材料")){
            llType.setVisibility(View.VISIBLE);
            queryType();
        }
        if(datanums.compareTo(BigDecimal.valueOf(3))==0){
            rvDatac.setVisibility(View.VISIBLE);
            rvDatab.setVisibility(View.VISIBLE);
        }else if(datanums.compareTo(BigDecimal.valueOf(2))==0){
            rvDatac.setVisibility(View.GONE);
            rvDatab.setVisibility(View.VISIBLE);
        }else{
            rvDatac.setVisibility(View.GONE);
            rvDatab.setVisibility(View.GONE);
        }

        initRecyclerView(rvItemLines, this);
        mItemLinesAdapter = new ItemLinesAdapter(qCformEntity.getQCFORM().getITEMLINES());
        mItemLinesAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        mItemLinesAdapter.isFirstOnly(true);
        rvItemLines.setAdapter(mItemLinesAdapter);

        initRecyclerView(rvDataLines, this);
        mDataLinesAdapter = new DataLinesAdapter(qCformEntity.getQCFORM().getDATALINES(),datanums);
        mDataLinesAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        mDataLinesAdapter.isFirstOnly(true);
        rvDataLines.setAdapter(mDataLinesAdapter);

        initRecyclerView(rvSpcLines, this);
        mItemSpcLinesAdapter = new ItemSpcLinesAdapter(qCformEntity.getQCFORM().getSPCLINES(),this);
        mItemSpcLinesAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        mItemSpcLinesAdapter.isFirstOnly(true);
        rvSpcLines.setAdapter(mItemSpcLinesAdapter);
        mItemSpcLinesAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                itemPosition = position;
                Bundle bundle= new Bundle();
                bundle.putSerializable("DATA",mItemSpcLinesAdapter.getItem(position));
                bundle.putSerializable("EDCNAMELIST",qCformEntity);
                bundle.putSerializable("LocationId",LocationId);
                Intent intent = new Intent(QC_TaskExecuteNextActivity.this, QC_DataAcquisitionActivity.class);
                intent.putExtras(bundle);
                startActivityForResult(intent, 0);
            }
        });
        getComments();
    }

    private void getComments() {
        FreeUI_EntityCallBack<BaseResponseBean<AdrefListEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<AdrefListEntity>>
                (new TypeToken<BaseResponseBean<AdrefListEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<AdrefListEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), false, getSupportFragmentManager())) {
                    for (AdrefListEntity.Adref adref : response.body().getResponse().getBody().getADREFLIST()) {
                        resultList.add(adref.getTEXT());
                    }
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<AdrefListEntity>> response) {
                super.onError(response);
                loadError(response.getException(),"ADREFLISTQUERY");
            }
        };

        JsonObject map = new JsonObject();
        map.addProperty("REFERENCETYPE","USER");
        map.addProperty("REFERENCENAME","CPC_Patrol_Comments");
        NetUtils.requestPostNet("CPC.ADREFLISTQUERY", "TRANSFERMES", this, map, callBack);
    }

    private void queryType() {
        FreeUI_EntityCallBack<BaseResponseBean<QCformEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<QCformEntity>>
                (new TypeToken<BaseResponseBean<QCformEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<QCformEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), false, getSupportFragmentManager())) {
                    typeList.addAll(response.body().getResponse().getBody().getMATERIALLIST());
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<QCformEntity>> response) {
                super.onError(response);
                loadError(response.getException(),"QCFORMMATERIALQUERY");
            }
        };

        JsonObject map = new JsonObject();
        map.add("QCFORM", new JsonParser().parse(new Gson().toJson(qCformEntity.getQCFORM())).getAsJsonObject());
        NetUtils.requestPostNet("CPC.QCFORMMATERIALQUERY", "TRANSFERMES", this, map, callBack);
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @OnClick({R.id.tvBaseSubmit,R.id.flType,R.id.flResultList,R.id.finallyResultList})
    public void onViewClicked(View view) {
        switch (view.getId()){
            case R.id.tvBaseSubmit:
                if (Type.equals("首检") && tvfinallyResult.equals("")){
                    showToast("首检结果不能为空", false);
                    return;
                }

                for (QCformEntity.QCFORMINFO.ITEMLINESINFO data:mItemLinesAdapter.getData()) {
                    if (!tvResult.getText().toString().equals("调机中") && !tvResult.getText().toString().equals("换产中")) {
                        if (data.getRESULT().equals("NA")) {
                            showToast("非换产中或非调机中表单无法输入NA", false);
                            return;
                        }
                    }
                    if (data.getRESULT().equals("")) {
                        showToast("请选择检验结果", false);
                        return;
                    }
                }

                String result = "";
                ArrayList<QCformEntity.QCFORMINFO.DATALINESINFO>  datalinesinfos = new ArrayList<>();
                for (QCformEntity.QCFORMINFO.DATALINESINFO datum : mDataLinesAdapter.getData()) {
                    if(!"ChangeMolding_Inspection_Daily".equals(qCformEntity.getQCFORM().getINSPECTTIMING())){
                        String dataType=datum.getDATATYPE();
                        if(!datum.getDATAC().equals("")){
                            String datac=datum.getDATAC();
                           if(dataType.equals("NUM")&&!datac.matches("-?\\d+(\\.\\d+)?")){
                               showToast(datum.getITEMNAME()+"数据3只能填数字，请重新填写", false);
                               return;
                           }
                        }if(!datum.getDATAB().equals("")){
                            String datab=datum.getDATAB();
                            if(dataType.equals("NUM")&&!datab.matches("-?\\d+(\\.\\d+)?")){
                                showToast(datum.getITEMNAME()+"数据2只能填数字，请重新填写", false);
                                return;
                            }
                        }if(!datum.getDATAA().equals("")){
                            String dataa=datum.getDATAA();
                            if(dataType.equals("NUM")&&!dataa.matches("-?\\d+(\\.\\d+)?")){
                                showToast(datum.getITEMNAME()+"数据1只能填数字，请重新填写", false);
                                return;
                            }
                        }
                    }
                   /* if (datum.getRESULT().equals("")){
                        result = result+datum.getITEMNAME()+",";
                    }else{
                        datalinesinfos.add(datum);
                    }*/
                   if(qCformEntity.getQCFORM().getSTEPNAME().startsWith("T")){
                       if(!datum.getRESULTFLAG().equals("")){
                           if(!datum.getRESULTFLAG().toUpperCase().equals("OK")&&!datum.getRESULTFLAG().toUpperCase().equals("NG")){
                               showToast(datum.getITEMNAME()+"结果只能填【OK】或【NG】", false);
                               return;
                           }
                       }
                       datalinesinfos.add(datum);
                   }else{
                       if(datanums.compareTo(BigDecimal.valueOf(3))==0){
                           if (datum.getDATAC().equals("")){
                               result = result+datum.getITEMNAME()+",\n";
                           }else{
                               if(datum.getDATAA().equals("")){
                                   showToast(datum.getITEMNAME()+"请填写数据1", false);
                                   return;
                               }
                               if(datum.getDATAB().equals("")){
                                   showToast(datum.getITEMNAME()+"请填写数据2", false);
                                   return;
                               }
                               datalinesinfos.add(datum);
                           }
                       }else if(datanums.compareTo(BigDecimal.valueOf(2))==0){
                           if (datum.getDATAB().equals("")){
                               result = result+datum.getITEMNAME()+",\n";
                           }else{
                               if(datum.getDATAA().equals("")){
                                   showToast(datum.getITEMNAME()+"请填写数据1", false);
                                   return;
                               }
                               datalinesinfos.add(datum);
                           }
                       }else{
                           if(!datum.getRESULTFLAG().equals("")){
                               if(!datum.getRESULTFLAG().toUpperCase().equals("OK")&&!datum.getRESULTFLAG().toUpperCase().equals("NG")){
                                   showToast(datum.getITEMNAME()+"结果只能填【OK】或【NG】", false);
                                   return;
                               }
                           }
                           if (datum.getDATAA().equals("")){
                               result = result+datum.getITEMNAME()+",\n";
                           }else{
                               datalinesinfos.add(datum);
                           }
                       }
                   }

                }
                if(mDataLinesAdapter.getData().size()>0&&datalinesinfos.size()==0){
                    showToast("数据项录入不能为空！", false);
                    return;
                }
               // FreeApi_DialogUtils.getConfirmAndCancelDialog(this, result.equals("") ? "请确认是否提交?" : result.substring(0,result.length()-1)+"\n数据填写不完整，请确认是否提交?", () -> {
                FreeApi_DialogUtils.getConfirmAndCancelDialog(this, result.equals("") ? "请确认是否提交?" : "有首检项目未录入数据，是否确认提交?", () -> {
                    FreeUI_EntityCallBack<BaseResponseBean<QCformEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<QCformEntity>>
                            (new TypeToken<BaseResponseBean<QCformEntity>>() {
                            }.getType(), getSupportFragmentManager(), this) {

                        @Override
                        public void onSuccess(Response<BaseResponseBean<QCformEntity>> response) {
                            super.onSuccess(response);
                            if (response.body().isSuccess(getApplicationContext(), false, getSupportFragmentManager())) {
                                QC_TaskExecuteActivity.setMessage("1");
                                if (response.body().getResponse().getBody().getRESULTFLAG().equals("NG")) {
                                    FreeUI_GeneralFragmentDialog tipDialog = FreeApi_DialogUtils.getConfirmDialog(MyApp.app, "确定", "首检结果不通过，系统自动创建需要执行的首检单据为：" + response.body().getResponse().getBody().getQCFORMID(), () -> {
                                        //finish();
                                    });
                                    tipDialog.show(getSupportFragmentManager(), "DIALOG");
                                } else {
                                    showToast("提交成功", true);
                                   // finish();
                                   // rvDataLines.removeAllViews();
                                    if(Type.equals("首检")){
                                        mDataLinesAdapter = new DataLinesAdapter(response.body().getResponse().getBody().getQCFORM().getDATALINES(),response.body().getResponse().getBody().getQCFORM().getDATANUMS());
                                        mDataLinesAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
                                        mDataLinesAdapter.isFirstOnly(true);
                                        rvDataLines.setAdapter(mDataLinesAdapter);
                                        tvfinallyResult.setText(response.body().getResponse().getBody().getQCFORM().getFINALLY_RESULT());
                                    }else{
                                        finish();
                                    }
                                }
                            }
                        }

                        @Override
                        public void onError(Response<BaseResponseBean<QCformEntity>> response) {
                            super.onError(response);
                            loadError(response.getException(), "QCFORMCOMPLETE");
                        }
                    };
                    JsonObject map = new JsonObject();
                    QCformEntity.QCFORMINFO data = new QCformEntity.QCFORMINFO();
                    data.setOBJECTRRN(qCformEntity.getQCFORM().getOBJECTRRN());
                    data.setQCFORMID(qCformEntity.getQCFORM().getQCFORMID());
                    data.setLOTID(qCformEntity.getQCFORM().getLOTID());
                    data.setINSPECTSTEPNAME(qCformEntity.getQCFORM().getINSPECTSTEPNAME());
                    data.setINSPECTTIMING(qCformEntity.getQCFORM().getINSPECTTIMING());
                    data.setINSPECTTYPE(qCformEntity.getQCFORM().getINSPECTTYPE());
                    data.setEQUIPMENTID(qCformEntity.getQCFORM().getEQUIPMENTID());
                    data.setLOCATIONID(qCformEntity.getQCFORM().getLOCATIONID());
                    data.setSTATE(qCformEntity.getQCFORM().getSTATE());
                    data.setNAME(qCformEntity.getQCFORM().getNAME());
                    data.setDESCRIPTION(qCformEntity.getQCFORM().getDESCRIPTION());
                    data.setSTEPNAME(qCformEntity.getQCFORM().getSTEPNAME());
                    data.setSTEPDESC(qCformEntity.getQCFORM().getSTEPDESC());
                    data.setCIRCUITNAME(qCformEntity.getQCFORM().getCIRCUITNAME());
                    data.setCUSTOMERCODE(qCformEntity.getQCFORM().getCUSTOMERCODE());
                    data.setMAINMATTYPE(qCformEntity.getQCFORM().getMAINMATTYPE());
                    data.setCOMMENTS2(tvResult.getText().toString());
                    data.setCOMMENT(etComment.getText().toString());
                    data.setDATANUMS(qCformEntity.getQCFORM().getDATANUMS());
                    if (llType.getVisibility() == View.VISIBLE && tvType.getText().toString().equals("")) {
                        showToast("请选择更换材料类型", false);
                        return;
                    }
                    data.setMATERIALTYPE(tvType.getText().toString());

                    ArrayList<QCformEntity.QCFORMINFO.ITEMLINESINFO> itemlinesinfos = new ArrayList<>();
                    itemlinesinfos.addAll(mItemLinesAdapter.getData());
                    data.setITEMLINES(itemlinesinfos);

//                    ArrayList<QCformEntity.QCFORMINFO.DATALINESINFO> datalinesinfos = new ArrayList<>();
//                    datalinesinfos.addAll(mDataLinesAdapter.getData());
//                    data.setDATALINES(datalinesinfos);
                    data.setDATALINES(datalinesinfos.size() == 0 ? null : datalinesinfos);

                    ArrayList<QCformEntity.QCFORMINFO.SPCLINESINFO> spclinesinfos = new ArrayList<>();
                    spclinesinfos.addAll(mItemSpcLinesAdapter.getData());
                    data.setSPCLINES(spclinesinfos);
                    data.setFINALLY_RESULT(tvfinallyResult.getText().toString());
                    map.addProperty("ACTIONTYPE","complete");
                    map.add("QCFORM", new JsonParser().parse(new Gson().toJson(data)).getAsJsonObject());
                    NetUtils.requestPostNet("CPC.QCFORMCOMPLETE", "TRANSFERMES", this, map, callBack);
                }, () -> {
                }).show(getSupportFragmentManager(), "QCFORMCOMPLETE");

//                if (!result.equals("")){
//                    showToast("项目("+result+")结果不能为空",false);
//                    return;
//                }
                break;
            case R.id.flType:
                if (mTypePop != null) {
                    if (mTypePop.isShowing()) {
                        mTypePop.dismiss();
                    }
                } else {
                    mTypePop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flType.getWidth(), typeList, ivType, (codeS, i) -> {
                        tvType.setText(codeS);
                    });
                }
                FreeApi_PopUtils.setArrowShow(ivType);
                mTypePop.showAsDropDown(flType, 0, 0);
                break;
            case R.id.flResultList:
                if (mResultPop != null) {
                    if (mResultPop.isShowing()) {
                        mResultPop.dismiss();
                    }
                } else {
                    mResultPop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flResultList.getWidth(), resultList, ivResultArrow, (codeS, i) -> {
                        tvResult.setText(codeS);
                    });
                }
                FreeApi_PopUtils.setArrowShow(ivResultArrow);
                mResultPop.showAsDropDown(flResultList, 0, 0);
                break;
            case R.id.finallyResultList:
                if (mfinallyResultPop != null) {
                    if (mfinallyResultPop.isShowing()) {
                        mfinallyResultPop.dismiss();
                    }
                } else {
                    mfinallyResultPop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), finallyResultList.getWidth(), finallyresultList, ivfinallyResultArrow, (codeS, i) -> {
                        tvfinallyResult.setText(codeS);
                    });
                }
                FreeApi_PopUtils.setArrowShow(ivfinallyResultArrow);
                mfinallyResultPop.showAsDropDown(finallyResultList, 0, 0);
                break;
            default:
                throw new IllegalStateException("Unexpected value: " + view.getId());
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 0 && resultCode == 1) {
            Bundle bundle = data.getExtras();
            QCformEntity.QCFORMINFO.SPCLINESINFO itemdata = (QCformEntity.QCFORMINFO.SPCLINESINFO) bundle.getSerializable("ITEMDATA");
            mItemSpcLinesAdapter.getItem(itemPosition).getSPCLINEITEMS().clear();
            mItemSpcLinesAdapter.getItem(itemPosition).setSPCLINEITEMS(itemdata.getSPCLINEITEMS());
            mItemSpcLinesAdapter.notifyDataSetChanged();

            int min = 0;
            int max = 0;
            if(itemdata.getSPCLINEITEMS().get(0).getDCDATA()!=null&&!itemdata.getSPCLINEITEMS().get(0).getDCDATA().equals("")){
                 min = Integer.valueOf(itemdata.getSPCLINEITEMS().get(0).getDCDATA());
                 max = Integer.valueOf(itemdata.getSPCLINEITEMS().get(0).getDCDATA());
            }
            for (QCformEntity.QCFORMINFO.SPCLINESINFO.QCFORMSPCLINE spcItem :itemdata.getSPCLINEITEMS()){
                if(spcItem.getDCDATA()!=null&&!spcItem.getDCDATA().equals("")){
                    int dcData = Integer.valueOf(spcItem.getDCDATA());
                    if (dcData < min) {
                        min = dcData;
                    }
                    if (dcData > max) {
                        max = dcData;
                    }
                }

            }

            List<QCformEntity.QCFORMINFO.DATALINESINFO> dataLines= mDataLinesAdapter.getData();
            for (QCformEntity.QCFORMINFO.DATALINESINFO datum :dataLines){
                if(datum.getITEMNAME().equals("TTV")){
                    datum.setDATAA((max-min)+"");
                }
            }
            mDataLinesAdapter = new DataLinesAdapter((ArrayList<QCformEntity.QCFORMINFO.DATALINESINFO>) dataLines,datanums);
            mDataLinesAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
            mDataLinesAdapter.isFirstOnly(true);
            rvDataLines.setAdapter(mDataLinesAdapter);
        }
    }

}
